<template>
  <!-- 区域表单弹窗 -->
  <a-modal
    :title="headerTitle"
    :visible.sync="dialogVisible"
    @cancel="handleCancel"
    width="900px"
  >
    <!-- 表单 -->
    <a-spin :spinning="loading">
      <a-form-model
        ref="ruleForm"
        :model="forms"
        :rules="rules"
        :labelCol="{ span: 8 }"
        :wrapperCol="{ span: 14 }"
        style="max-height: 500px; overflow: auto"
      >
        <div id="dialogDistrictBox">
          <a-row>
            <a-col
              :lg="12"
              :md="12"
              :sm="12"
            >
              <a-form-model-item
                prop="dutySubcontractor"
                label="分包商"
              >
                <div
                  v-if="editModel == 2"
                  style="margin-top: -3px"
                >{{ forms.dutySubcontractorName }}</div>
                <select-subcontractor
                  v-if="dialogVisible && editModel != 2"
                  :form="form"
                  showSearch
                  :disabled="editModel == 2"
                  :option.sync="dutySubcontractor"
                  v-model="forms.dutySubcontractor"
                ></select-subcontractor>
              </a-form-model-item>
            </a-col>
            <a-col
              :lg="12"
              :md="12"
              :sm="12"
            >
              <a-form-model-item
                prop="dutyPeople"
                label="责任人"
              >
                <div
                  v-if="editModel == 2"
                  style="margin-top: -3px"
                >
                  <ellipsis
                    tooltip
                    :length="20"
                  >{{ forms.dutyPeopleName }}</ellipsis>
                </div>
                <SelectPersonByProject
                  v-if="dialogVisible && editModel != 2"
                  :id="form.branchCompanyId"
                  :disabled="editModel == 2"
                  v-model="forms.dutyPeople"
                  mode="multiple"
                  :maxTagCount="2"
                  statusCode="0"
                  :projectId="form.projectId"
                  :showSearch="true"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col
              :lg="24"
              :md="24"
              :sm="24"
            >
              <a-form-model-item
                prop="rectificationPeople"
                label="整改人"
              >
                <div
                  v-if="editModel == 2"
                  style="margin-top: -3px"
                >
                  <a-tag
                    style="font-size:16px;"
                    v-for="(item, index) in forms.rectificationPeopleName"
                    :key="index"
                  >{{ item }}</a-tag>
                  <span v-if="!forms.rectificationPeople || forms.rectificationPeople.length == 0">无</span>
                </div>
                <a-spin
                  :spinning="spinning || spinningTwo"
                  v-else
                  style="max-height: 200px; overflow-y: auto"
                >
                  <a-checkbox-group
                    v-model="forms.rectificationPeople"
                    style="margin-top: 6px"
                  >
                    <a-checkbox
                      v-for="i in rectificationPeoples"
                      :key="i.id"
                      :value="i.id"
                    >
                      <ellipsis
                        tooltip
                        :length="20"
                      >
                        {{ i.name }}
                      </ellipsis>
                    </a-checkbox>
                  </a-checkbox-group>
                  <span v-if="!rectificationPeoples || rectificationPeoples.length == 0">无</span>
                </a-spin>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col
              :lg="12"
              :md="12"
              :sm="12"
            >
              <a-form-model-item
                prop="status"
                label="状态"

              >
                <a-select
                  :disabled="editModel == 2"
                  v-model="forms.status"
                >
                  <a-select-option :value="'1'">启用</a-select-option>
                  <a-select-option :value="'0'">停用</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col
              :lg="12"
              :md="12"
              :sm="12"
            >
              <a-form-model-item
                prop="projectConstructionTypeId"
                label="工程类别"
              >
               <a-select v-model="forms.projectConstructionTypeId" @change="changeProjectConstruction" :disabled="editModel == 2">
                <a-select-option
                  v-for="item in projectList"
                  :value="item.newId || item.id"
                  :key="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
              </a-form-model-item>
            </a-col>
            <a-col
              
              :lg="12"
              :md="12"
              :sm="12"
            >
              <a-form-model-item
                prop="partIds"
                label="施工内容"
              >
                <!-- :isReturnArrId="editModel*1>0?true:false" -->
                <SelectTreeConstruction
                  :labels.sync="forms.partNames"
                  :labelInValue="true"
                  :projectId="form.projectId"
                  :form="form"
                  :typeId="forms.projectConstructionTypeId"
                  :treeCheckable="true"
                   v-model="forms.partIds"
                   :isJz="isJz"
                  :disabled="editModel == 2"

                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col
              :lg="24"
              :md="24"
              :sm="24"
            >
              <a-form-model-item
                prop="dutyAreaDescription"
                label="责任区域描述"
                :labelCol="{ span: 4 }"
                :wrapperCol="{ span: 19 }"
              >
                <BaseInput
                  :maxLength="300"
                  :disabled="editModel == 2"
                  v-model="forms.dutyAreaDescription"
                  type="textarea"
                  :rows="6"
                ></BaseInput>
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
      </a-form-model>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div
      slot="footer"
      class="btn_box"
    >
      <a-button
        :loading="loading"
        v-if="editModel != 2"
        type="primary"
        class="button_right"
        @click="handleOk"
      >提交</a-button>
      <a-button
        type="primary"
        @click="handleCancel"
      >关闭</a-button>
    </div>
  </a-modal>
</template>

<script>
import cloneDeep from 'lodash.clonedeep' // 深拷贝
import { Ellipsis } from '@/components' // 表格
import { set } from '@/api/quality/currency' // api
import { men } from '@/api/quality/quality' // api
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分包商
// import SelectDutyPeople from '@/components/Select/SelectDutyPeople' // 分包商
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import SelectTreeConstruction from '@/components/Select/SelectTreeConstruction'
import { queryLists } from '@/api/quality/projectDivision' // api

export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubcontractor,
    // SelectDutyPeople,
    SelectTreeConstruction,
    SelectPersonByProject,
    Ellipsis
  },
  props: {
    // 操作类型
    editModel: {
      type: [String, Number],
      default() {
        return 0
      }
    },
    // 显隐控件
    visible: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 表单
    form: {
      type: Object,
      default() {
        return {}
      }
    },
    // 标题
    headerTitle: {
      type: String,
      default() {
        return ''
      }
    },
    // 模块类型：0 质量；1 安监
    moduleType: {
      type: [String, Number],
      default() {
        return 0
      }
    },
    //施工内容是否必填
    isMandatory:{
      type: Boolean,
      default() {
        return false
      }
    }
  },
  computed: {
    spinningTwo() {
      return this.rectificationPeoples?.length == 0 && this.editModel == 2
    },
    rectificationPeople() {
      let rectificationPeople = []
      this.forms.rectificationPeople && (rectificationPeople = [...this.rectificationPeoples]?.filter((item) => this.forms.rectificationPeople.includes(item.id)) ?? [])
      return rectificationPeople
    },
    
    // 与父组件绑定visible
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (e) {
        this.$emit('update:visible', e)
      }
    }
  },
  data() {
    return {
      forms: {
        projectConstructionTypeId:'',
        partIds:[],
      }, // 表单
      loading: false,
      dutySubcontractor: {}, // 分包商选中项
      spinning: false, // 整改人加载
      rectificationPeoples: [], // 整改人列表
      rules: {
        dutySubcontractor: [{ required: true, message: '请选择分包商', trigger: 'change' }],
        dutyPeople: [{ required: true, message: '请选择责任人', trigger: 'change' }],
        rectificationPeople: [{ type: 'array', required: true, message: '请选择整改人', trigger: 'blur' }],
        // partIds: [{ type: 'array', required: true, message: '请选择施工内容', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        dutyAreaDescription: [{ required: true, message: '请填写责任区域描述', trigger: 'change' }],
        projectConstructionTypeId:[{ required: true, message: '请选择工程类别', trigger: 'change' }],
      },
      projectList:[], //工程类别
      projectConstructionTypeId:null, //工程类别 id
      findSourceId:null, //找到对应的工程类别sourceId
      isJz:false, //是否调用基础分部分项
    }
  },
  mounted(){
    if(this.isMandatory){
      this.rules.partIds = [{ type: 'array', required: true, message: '请选择施工内容', trigger: 'change' }]
    }
  },
  methods: {
    //获取工程类别数据
    getProjectList(){
       let obj = {projectId:this.form.projectId};
       queryLists(obj).then((res)=>{
         if(res.code == 200){
          this.projectList = res.data;
          //设置默认值
          if(this.projectList.length && this.editModel*1<1){
            this.$set(this.forms,'projectConstructionTypeId',this.projectList[0].id) 
          }
         }
       })
    },
    changeProjectConstruction(val){
     this.forms.partIds = [];
    },
    // 返回数组id
    returnArrId(data){
        this.forms.partIds = data;
    },
    handleOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$emit('confirm', this.forms)
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    handleCancel() {
      this.dialogVisible = false
    },
    // 切换分包商获取整改人
    handleChange(reset = true) {
      this.$nextTick(() => {
        let id = this.dutySubcontractor.subContractorOrgId
        this.spinning = true
        // reset && this.$set(this.forms, 'rectificationPeople', [])
        men
          .getList({ subContractorId: this.forms.dutySubcontractor, projectId: this.form.projectId })
          .then((res) => {
            this.spinning = false
            if (res.data?.length > 0) {
              this.rectificationPeoples = res.data
            } else {
              this.rectificationPeoples.length > 0 && (this.rectificationPeoples = res.data)
            }
          })
          .catch((res) => {
            this.spinning = false
          })
      })
    }
  },
  watch: {
    dutySubcontractor(e) {
      if (e && Object.keys(e)?.length > 0 && e.subContractorOrgId) {
        this.handleChange()
      } else {
        this.forms.rectificationPeople?.length > 0 && (this.forms.rectificationPeople = [])
        this.rectificationPeoples.length > 0 && (this.rectificationPeoples = [])
      }
    },
    'forms.projectConstructionTypeId':{  //监听工程类别
        handler(val) {
        if(val){
           if(this.editModel*1<2){  //编辑和新增false
            this.isJz = false; 
           }
           else{
             this.isJz = true;
           }
         }else{
          this.isJz = true;
         }
        },
   
    },
    visible(e) {
      if (e) {
        this.$nextTick(() => {
          // 若操作为查看和编辑
          if (this.editModel != 0) {
            this.loading = true
            set
              .getDetail({
                id: this.form.id
              })
              .then((res) => {
                this.loading = false
                if (res.code == 200) {
                  this.forms = res.data;
                  this.projectConstructionTypeId = this.$clone(this.forms.projectConstructionTypeId);
                  if(this.projectList.length){    //对历史数据回显不对处理
                    this.projectList.map((item)=>{
                       if(item.sourceId==this.projectConstructionTypeId){
                         this.findSourceId = item.sourceId;
                         item.newId = item.sourceId;
                         console.log(this.editModel,'11')
                         if(this.editModel*1<2){  //查看2
                           this.forms.partIds = [];
                         }
                           //如果sourceId等于类别id，那么就是基准分部分项数据，编辑时就要清空
                         //this.forms.projectConstructionTypeId = item.id;
                       }
                    });
                  }
                }
              })
              .catch((res) => {
                this.loading = false
              })
          } else {
            this.forms = cloneDeep(this.form)
          }
        })
      this.getProjectList();
      } else {
        this.forms = {}
        this.rectificationPeoples = []
        this.dutySubcontractor = []
        // 初始化表单
        this.$refs.ruleForm.clearValidate()
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.ant-checkbox-wrapper {
  margin-left: 0;
  width: 160px;
  overflow: hidden;
  height: 24px;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
